﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CServiceStack.Common.Web;
using CServiceStack.ServiceHost;

namespace SomeServices
{
    class ETagResponseFilter : Attribute, IHasResponseFilter
    {
        public IHasResponseFilter Copy()
        {
            return this;
        }

        public int Priority
        {
            get { return -1; }
        }

        public void ResponseFilter(IHttpRequest req, IHttpResponse res, object response)
        {
            string etag = req.Headers[HttpHeaders.IfNoneMatch];
            string ifModifiedSince = req.Headers[HttpHeaders.IfModifiedSince];
            if (!string.IsNullOrEmpty(etag)&&!string.IsNullOrEmpty(ifModifiedSince))
            {
                res.AddHeader(HttpHeaders.ETag, etag);
                res.AddHeader(HttpHeaders.LastModified, req.Headers[HttpHeaders.IfModifiedSince]);
                response = Activator.CreateInstance(response.GetType());
                res.StatusCode = 304;
                //res.StatusDescription = "Not Modified";
            }
            else
            {
                res.AddHeader(HttpHeaders.ETag, Guid.NewGuid().ToString());
                res.AddHeader(HttpHeaders.LastModified, DateTime.Now.ToUniversalTime().ToString());
            }
        }
    }
}
